import { ref, onUnmounted, getCurrentInstance } from 'vue'

/**
 * 节流Hook
 * @returns {Function} 节流函数
 */
const useThrottle = () => {
    const timer = ref(null)
    const lastExecTime = ref(0)
    const instance = getCurrentInstance()

    const throttle = (fn, delay = 300, ...args) => {
        const now = Date.now()
        const remaining = delay - (now - lastExecTime.value)

        if (remaining <= 0) {
            if (timer.value) {
                clearTimeout(timer.value)
                timer.value = null
            }
            lastExecTime.value = now
            fn(...args)
        } else if (!timer.value) {
            timer.value = setTimeout(() => {
                lastExecTime.value = Date.now()
                timer.value = null
                fn(...args)
            }, remaining)
        }
    }

    // 组件卸载时自动清除定时器
    onUnmounted(() => {
        if (timer.value) {
            clearTimeout(timer.value)
            timer.value = null
        }
        // 小程序环境额外处理
        if (instance?.proxy?.$scope?.onUnload) {
            instance.proxy.$scope.onUnload = () => {
                if (timer.value) clearTimeout(timer.value)
            }
        }
    })

    return { throttle }
}

export { useThrottle }
